<template>
	<view class="ll-sendbutton" @click="onClickSend">
		<text
			:style="{color:status==0?textColor:textColorDisable}">{{ status==0 || status==1?'获取验证码':`${remainTime}秒后重新获取` }}</text>
	</view>
</template>

<script>
	export default {
		name: "ll-sendbutton",
		emits: ['clickSend'],
		props: {
			/**
			 * 可点击时字体颜色
			 */
			textColor: {
				type: String,
				default: '#000'
			},
			/**
			 * 不可点击时字体颜色
			 */
			textColorDisable: {
				type: String,
				default: '#95969A'
			},
			/**
			 * 倒计时最大时长
			 */
			maxTime: {
				type: Number,
				default: 60
			}
		},

		data() {
			return {
				status: 0, //按钮状态,0:可发送，1：正在发送，2：已发送
				remainTime: 0, //剩余的时间(秒)，
				timmer: 0
			};
		},

		methods: {
			onClickSend() {
				if (this.status == 0) {
					this.$emit('clickSend', {})
				} else if (this.status == 1) {
					uni.showToast({
						icon: 'none',
						title: '正在发送验证码，请稍后再试'
					})
				}
			},

			/**
			 * 用于请求发送验证码接口之前，防止在请求发送验证码的过程中，重复请求接口
			 */
			prepare() {
				this.status = 1
			},

			/**
			 * 发送验证码成功后调用，开始倒计时
			 */
			start() {
				let that = this
				this.remainTime = this.maxTime
				this.status = 2
				this.timmer = setInterval(function() {
					if (that.remainTime <= 0) {
						that.reset()
					} else {
						that.remainTime = that.remainTime - 1
					}
				}, 1000);
			},

			/**
			 * 在发送验证码失败后调用，恢复状态
			 */
			reset() {
				if (this.timmer) {
					clearInterval(this.timmer)
				}
				this.timmer = 0
				this.remainTime = 0
				this.status = 0
			},

			// #ifdef VUE2
			beforeDestroy() {
				this.reset()
			},
			// #endif
			
			// #ifdef VUE3
			unmounted() {
				this.reset()
			}
			// #endif
		}
	}
</script>

<style lang="scss">
	.ll-sendbutton {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-end;
		min-width: 220rpx;

		text {
			font-size: 28rpx;
			text-align: right;
		}
	}
</style>